import { createStore, combineReducers, applyMiddleware, compose, Action } from 'redux';
import thunk from 'redux-thunk';
import global from './global';
import user from './user';
import dic from './dic';
import { removeToken, removeUserInfo } from '@/utils/auth';
import { types } from './user';

const modulesRedux = require.context('../sections', true, /redux.ts$/)

const composeEnhancers = (window && (window as any)).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? (window && (window as any)).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
let reducer: any = {};

modulesRedux.keys().reduce((modules: object, modulePath: string) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\/redux\.\w+$/, '$1')
  const value = modulesRedux(modulePath);
  if (value.default) reducer[moduleName] = value.default;
  return modules
}, {})

const reducers = {
  user,
  global,
  dic,
  ...reducer
}

const appReducer = combineReducers(reducers)

export type RootState = ReturnType<typeof reducers>

const rootReducer = (state: RootState, action: Action) => {
  // 退出登录 清空所有store
  if (action.type === types.USER_LOGOUT) {
    state = undefined;
    removeToken();
    removeUserInfo();
  }
  return appReducer(state, (action as never));
};

const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));

export default store;

